#include "GuiElementRenderer.h"
#include "SDL_opengl.h"
#include <iostream>

namespace k2graphics
{

GuiElementRenderer::GuiElementRenderer()
{
	// don't do anything special here...
}

void GuiElementRenderer::renderObject(RenderData* data, GraphicsInternals* gi)
{
	// we should have five float values (x,y,theta,width,height) and one
	// byte value (texture)

	if(data->numBytes < 1 || data->numFloats < 8)
		return;

	//std::cout << "Rendering CBBR...";

	float x1 = data->floatData[0];
	float y1 = data->floatData[1];
	float x2 = data->floatData[2];
	float y2 = data->floatData[3];

	float u1 = data->floatData[4];
	float v1 = data->floatData[5];
	float u2 = data->floatData[6];
	float v2 = data->floatData[7];

	int textureID = data->byteData[0];

	// this is a bit of a hack: if the texture byte is 255, that means it
	// wants an extended texture, so look in the first int data instead
	if(textureID == 255)
	{
		if(data->numInts < 1)
			return;

		textureID = data->intData[0];
	}

	AbstractTexture* curTexture = gi->textureDepot.getTexture(textureID);

	if(!curTexture)
		return;

	// first, use matrices to put ourselves in the right position
	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
	//glTranslatef(x, y, 0.0f);
	//glRotatef(theta, 0.0f, 0.0f, 1.0f);

	// enable texturing (replace mode)
	glEnable(GL_TEXTURE_2D);
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

	if(data->numBytes < 5)
		glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
	else
	{
		float r = data->byteData[1] / 255.0f;
		float g = data->byteData[2] / 255.0f;
		float b = data->byteData[3] / 255.0f;
		float a = data->byteData[4] / 255.0f;

		//std::cout << "rbga " << r << " " << g << " " << b << " " << a << std::endl;

		glColor4f(r, g, b, a);
	}

	// enable blending
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);


	// bind our texture
	glBindTexture(GL_TEXTURE_2D, curTexture->getRawGLTexture());

	// draw our thing!
	float tx = 0.0f;
	float ty = 0.0f;

	glBegin(GL_QUADS);

	curTexture->getRawTextureCoordinates(u1, v2, tx, ty);
	//curTexture->getRawTextureCoordinates(1.0, 0.0, tx, ty);
	glTexCoord2f(tx, ty);
	glVertex2f(x1, y2);

	curTexture->getRawTextureCoordinates(u1, v1, tx, ty);
	//curTexture->getRawTextureCoordinates(1.0, 1.0, tx, ty);
	glTexCoord2f(tx, ty);
	glVertex2f(x1, y1);

	curTexture->getRawTextureCoordinates(u2, v1, tx, ty);
	//curTexture->getRawTextureCoordinates(0.0, 1.0, tx, ty);
	glTexCoord2f(tx, ty);
	glVertex2f(x2, y1);

	curTexture->getRawTextureCoordinates(u2, v2, tx, ty);
	//curTexture->getRawTextureCoordinates(0.0, 0.0, tx, ty);
	glTexCoord2f(tx, ty);
	glVertex2f(x2, y2);

	glEnd();

	// disable texturing
	glDisable(GL_TEXTURE_2D);

	// undo our matrix stuff
	glPopMatrix();
}

}
